%{
#include <stdio.h>
#include <stdlib.h>
#include "globals.h"
int bloco_senao = 0;
%}

%token TATRIB TID TVARIAVEIS TINTEIRO TCADEIA TSE TENTAO TENQUANTO TIMPRIME TLEIA TINICIO TFIM TPV TDP TVIRGULA TAbreP TFechaP TSENAO TIntValue TStrValue
TASPAS TIGUAL TMAIOR TMENOR TMAIORIGUAL TMENORIGUAL TOU TAND TNOT TMULT TDIV TADD TSUB TNUM TLABEL

%right TATRIB 
%left TADD TSUB TOU TNOT TIGUAL TMENOR TMAIOR
%left TMULT TDIV TAND


%union {
	double numval;
	char *strval;
}
	
%%

Programa: Declaracoes Bloco { 
	#ifdef DEBUG
	dump_symbol_table();
	#endif
	printf("\n\n");
	cmd_node_to_source(list);
}
	;

Declaracoes: TVARIAVEIS Decls 
	;

Decls: TID ListaID { 
		declare_var($<strval>1);
	} 
	;

ListaID: TVIRGULA TID ListaID { 
		declare_var($<strval>2);
	} 

	| TDP Tipo TPV 
	;

Tipo: TINTEIRO
	| TCADEIA
;

Bloco: TINICIO ListaCmd TFIM  
;

BlocoSe: TINICIO ListaCmd TFIM { 
		cmd_node_add(list, LABEL_BRANCH_WHEN_FALSE, 0, 0); 
	}
;

BlocoSenao: TINICIO ListaCmd TFIM { 
		cmd_node_add(list, GOTO, 0, 0); 
		cmd_node_add(list, LABEL_BRANCH_WHEN_FALSE, 0, 0); 
	}
;

ListaCmd: Comando
	| ListaCmd TPV Comando
	;

Comando: CmdSe 
	| CmdEnquanto 
	| CmdAtrib 
	| CmdEscrita
	| Etiqueta Comando
	;

CmdAtrib: TID TATRIB ExprMat { 
	if (int_found) {
		cmd_node_add(list, ISTORE, get_position_by_name($<strval>1), 0);
		int_found = 0;
		var_index++;
	}													

	else if (id_found) {
		cmd_node_add(list, ISTORE, get_position_by_name($<strval>1), 0);
		id_found = 0;
		var_index++;
	}
} 
	;

CmdEscrita: TIMPRIME TAbreP TIntValue TFechaP {}
	| TIMPRIME TAbreP TStrValue TFechaP {}
	;
	
	
CmdSe: 	TSE TAbreP ExprLog TFechaP TENTAO BlocoSe	
	| TSE TAbreP ExprLog TFechaP TENTAO BlocoSenao TSENAO BlocoSe
	;


CmdEnquanto: TENQUANTO TAbreP ExprLog TFechaP Bloco
	;

Fator: TIntValue { 
		int_found = 1; 
		cmd_node_add(list, BIPUSH, get_position_by_name($<strval>1), 0);
	} 

	| TID { 
		id_found = 1; 
		cmd_node_add(list, ILOAD, get_position_by_name($<strval>1), 0);
	} 

	| TAbreP ExprMat TFechaP {}
	;

	
ExprMat: ExprMat TADD ExprMat {
		cmd_node_add(list, IADD, 0, 0);
	}

	| ExprMat  TSUB ExprMat {
		cmd_node_add(list, ISUB, 0, 0);
	}
	
	| ExprMat  TMULT ExprMat {
		cmd_node_add(list, IMUL, 0, 0);
	}

	| ExprMat  TDIV ExprMat {
		cmd_node_add(list, IDIV, 0, 0);
	}

	| Fator
	;

	
ExprRel: ExprRel TMENOR ExprRel {}
	| ExprRel TMAIOR ExprRel { 
		cmd_node_add(list, IF_ICMPGT, 0, 0);
	}
	
	| ExprRel TIGUAL ExprRel { 
		cmd_node_add(list, IF_ICMPEQ, 0, 0);
	}

	| ExprMat
	;

ExprLog: ExprLog TAND ExprLog {}
	| ExprLog TOU ExprLog {}
	| TNOT ExprLog {}
	| ExprRel
	;	
	
Etiqueta: TLABEL {
		printf("encontrou label: %s", $<strval>1);
		declare_var($<strval>1);	
}
	;	
%%
#include "lex.yy.c"

int yyerror (char *str)
{
	printf("%s - antes %s\n", str, yytext);
	
} 		 

int yywrap()
{
	return 1;
}
